
<template>
  <div class="fra-monitoring-setting" :style="`width: calc(100% - ${sideMenuWidth} - 33px)`">

    <div class="fra-monitoring-setting-main">
      <div>将在 {{ now }} 秒后刷新</div>
      <a-form-model
        ref="dataForm"
        :model="dataForm"
        :rules="dataFormRules"
      >
        <!-- 筛选条件与查询 -->
        <a-row :gutter="12">
          <a-col :span="6">
            <a-form-model-item label="机型" prop="model">
              <airModel v-model="dataForm.model" mode="default" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="机队" prop="fleet">
              <a-select
                v-model="dataForm.fleet"
                show-arrow
                style="minWidth: 130px"
                placeholder="ALL"
                allow-clear
              >
                <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
                <a-select-option v-for="item in ftmFleetList" :key="item.id" :value="item.name">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="重要性" prop="priority">
              <a-select
                v-model="dataForm.priority"
                show-arrow
                style="minWidth: 130px"
                placeholder="ALL"
                mode="default"
                allow-clear
              >
                <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
                <a-select-option v-for="item in priorityList" :key="item.id" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="事件类型" prop="type">
              <!-- <a-select
                v-model="dataForm.type"
                show-arrow
                style="minWidth: 130px"
                placeholder="ALL"
                mode="multiple"
                :max-tag-count="1"
                allow-clear
              >
                <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
                <a-select-option v-for="item in eventListData" :key="item.id" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select> -->
              <eventList v-model="dataForm.type" placeholder="ALL" :mul="true" />
            </a-form-model-item>
          </a-col>

          <a-col :span="24">

            <a-row>
              <a-col :span="6">
                <a-form-model-item label="是否显示EF事件" prop="isEf">

                  <a-switch v-model="isEf" size="small">
                    <a-icon slot="checkedChildren" type="check" style="font-size:10px" />
                  </a-switch>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="是否显示最新消息" prop="isNow">

                  <a-switch v-model="isNow" size="small">
                    <a-icon slot="checkedChildren" type="check" style="font-size:10px" />
                  </a-switch>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="静音" prop="isMute">

                  <a-switch v-model="isMute" size="small">
                    <a-icon slot="checkedChildren" type="check" style="font-size:10px" />
                  </a-switch>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="是否显示状态" prop="isActivity">

                  <a-switch v-model="isActivity" size="small">
                    <a-icon slot="checkedChildren" type="check" style="font-size:10px" />
                  </a-switch>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="6" class="mb-0">
            <a-form-model-item label="起飞机场" prop="dep">
              <airportList v-model="dataForm.dep" type="dep" mode="default" />
            </a-form-model-item>
          </a-col>
          <a-col :span="1" class="is-and-or mb-0">
            <a-form-model-item prop="isAndOr">
              <a-radio-group v-model="dataForm.isAndOr">
                <a-radio :style="radioStyle" :value="0">
                  And
                </a-radio>
                <a-radio :style="radioStyle" :value="1">
                  Or
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" class="mb-0">
            <a-form-model-item label="到达机场" prop="arr">
              <airportList v-model="dataForm.arr" type="arr" mode="default" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="3">
            <a-form-model-item label="Other Item" prop="otherItem">

              <a-switch v-model="otherItem" size="small">
                <a-icon slot="checkedChildren" type="check" style="font-size:10px" />
              </a-switch>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="6" class="mb-0 pt-18">
            <a-form-model-item label=" ">
              <a-button type="default" ghost :loading="fleetMonitorByStatusLoading" @click="resetHandler">
                清除
              </a-button>
              <a-button type="primary" class="ml-15" :loading="fleetMonitorLoading" @click="submitHandler">
                提交
              </a-button>
              <a-button type="primary" class="ml-15" :loading="fleetMonitorLoading" @click="nexHandler">
                下一条
              </a-button>
            </a-form-model-item>

          </a-col>

        </a-row>
      </a-form-model>

    </div>
    <div v-if="fleetMonitorDataF.eventId" class=" mt-16">
      <a-row type="flex" class="c-grid-box-fms">
        <a-col class="c-g-b-wd1">
          <div class="fw-b fs-12 color-r">机号</div>
          <a class="fs-18 fw-b  numbers" @click="(e)=>reportHandler(e, fleetMonitorDataF, 'flightLegHistoryVisible', 0)">{{ fleetMonitorDataF.tailnumber ||'--' }}</a>
        </a-col>
        <a-col class="c-g-b-wd2">
          <div class="fw-b fs-12 color-r">机队</div>
          <div class="fs-18 fw-b color-title  numbers">{{ fleetMonitorDataF.fleet||'--' }}</div>
        </a-col>
        <a-col class="c-g-b-wd3">
          <div class="fw-b fs-12 color-r">航班</div>
          <a class="fs-18 fw-b   numbers" @click="(e)=>reportHandler(e, fleetMonitorDataF, 'flightLegDetailsVisible', 0)">{{ fleetMonitorDataF.flightNo||'--' }}</a>
        </a-col>
        <a-col class="c-g-b-wd4">
          <div class="fw-b fs-12 color-r">航段</div>

          <div class="fs-18 fw-b color-title  numbers">{{ $legHandler(fleetMonitorDataF.leg, fleetMonitorDataF.totalLeg) }}</div>
        </a-col>
        <a-col class="c-g-b-wd5">
          <div class="fw-b fs-12 color-r">更新时间</div>
          <div class="fw-b fs-13">
            <span class="fs-18 color-title mr-4 numbers">{{ fleetMonitorDataF.latestAcarsTime? $moment.utc(fleetMonitorDataF.latestAcarsTime).format('HH:mm') :'--' }}</span>
            <span class="color-s  numbers">{{ fleetMonitorDataF.latestAcarsTime? $moment.utc(fleetMonitorDataF.latestAcarsTime).format('MM-DD'):'--' }}</span>
          </div>
        </a-col>
        <a-col class="c-g-b-wd6 pt-10">
          <div class="text-c"><oooiSvg :step="oooiStep.step" :time="oooiStep.time" /></div>
        </a-col>

        <a-col class="c-g-b-wd7 ">
          <div class="text-r mt-18 pr-30">
            <reportList :report-handler="reportHandler" :record="fleetMonitorDataF" :index="0" :events="true" />
          </div>
        </a-col>
      </a-row>
    </div>
    <div v-if="fleetMonitorDataF.eventId" class="ed-details-item-main-box">

      <a-row class="ed-details-item-box" :style="{'border-color':priorityHandler(fleetMonitorDataF.priority).color}">
        <a-col :span="24">
          <a-row class="d-flex-i ai-center">
            <a-col :span="2">
              <noticePriorityIcon :is-etops="fleetMonitorDataF.isEtops" :priority="fleetMonitorDataF.priority" :msg-type="fleetMonitorDataF.name" />
            </a-col>
            <a-col :span="4">
              <div class="fw-b text-color-21252e">{{ fleetMonitorDataF.name }}</div>
            </a-col>
            <a-col :span="6">
              <span class="fw-b  fs-14 va-top text-color-21252e">{{ fleetMonitorDataF.code||'--' }}</span>
            </a-col>
            <a-col :span="12">
              <span class="fw-b  fs-14 va-top text-color-21252e"> {{ fleetMonitorDataF.description||'--' }}</span>

            </a-col>
          </a-row>
        </a-col>
        <a-col :span="22" :offset="2" class="mt-8">

          <div class="d-flex">
            <div class="ed-details-item">
              <div slot="label" class="fs-12 text-color-505363">状态</div>
              <div class="fs-12 text-color-505363">{{ activeHandler(fleetMonitorDataF.activity)||'--' }}</div>
            </div>
            <div class="ed-details-item2">
              <div slot="label" class="fs-12 text-color-505363">飞行阶段</div>
              <div class="fs-12 text-color-505363">{{ fleetMonitorDataF.phase||'--' }}</div>
            </div>
            <div class="ed-details-item3">
              <div slot="label" class="fs-12 text-color-505363">消息时间</div>
              <div class="fs-12 text-color-505363">{{ fleetMonitorDataF.msgTime||'--' }}</div>
            </div>
            <div class="ed-details-item4">
              <div slot="label" class="fs-12 text-color-505363">Detected by</div>
              <div class="fs-12 text-color-505363">{{ fleetMonitorDataF.detectedBy||'--' }}</div>
            </div>
          </div>

        </a-col>
      </a-row>
    </div>
    <div class="alert-sc" :style="`background: linear-gradient(to right, ${fmsBack} 0%, transparent 60%);width:${width}px`" />
    <div class="alert-sc-right" :style="`background: linear-gradient(to left, ${fmsBack} 0%, transparent 60%);width:${rWidth}px`" />
    <!-- <a-col :span="6">
          <a-form-model-item label="FDE类型">
            <a-select show-arrow       v-model="dataForm.arr"
              style="minWidth: 130px"
              placeholder="请选择"
              allow-clear
            >
              <a-select-option v-for="selectItem in arrList" :key="selectItem.id" :value="selectItem.name">
                {{ selectItem.name }}
              </a-select-option>
            </a-select>

          </a-form-model-item>
        </a-col> -->

  </div>
</template>

<script>
import { mapState, mapActions, mapGetters, mapMutations } from 'vuex';
import { priorityList } from '@/pages/common/constant.js';
import oooiSvg from '@/pages/components/oooi';
import eventList from '@/pages/components/eventList';
import airportList from '@/pages/components/airportList';
import airModel from '@/pages/components/airModel';
import reportList from '@/pages/fraMonitoring/reportList';

export default {
  components: {
    eventList,
    airportList,
    airModel,
    oooiSvg,
    reportList

  },
  data() {
    const validatePassDep = (rule, value, callback) => {
      if (this.dataForm.isAndOr === 0) {
        if (this.dataForm.arr && this.dataForm.dep) {
          callback();
        } else {
          callback(new Error('请选择起飞机场'));
        }
      } else {
        callback();
      }
    };
    const validatePassArr = (rule, value, callback) => {
      if (this.dataForm.isAndOr === 0) {
        if (this.dataForm.arr && this.dataForm.dep) {
          callback();
        } else {
          callback(new Error('请选择到达机场'));
        }
      } else {
        callback();
      }
    };
    return {

      width: 200,
      rWidth: 200,
      currentRow: {},
      radioStyle: {
        display: 'block',
        height: '20px',
        lineHeight: '20px'
      },
      setTime: -1,
      dataForm: {
        isAndOr: 1,
        isEf: 1,
        isNow: 1,
        isMute: 1,
        isActivity: 1,
        otherItem: 0
      },
      priorityList,
      eventTypeT: '',
      now: 60,
      dataFormRules: Object.freeze({

        dep: [
          { validator: validatePassDep, trigger: 'change' }
        ],
        arr: [
          { validator: validatePassArr, trigger: 'change' }
        ]
      })
    };
  },
  computed: {
    ...mapGetters('setting', ['sideMenuWidth']),
    ...mapState('fraMonitoringSetting', [
      'fleetMonitorLoading',
      'fleetMonitorByStatusLoading',
      'eventListData',
      'fleetMonitorData',
      'eventListLoading',
      'allAcIndex',
      'configId',
      'configData'
    ]),
    ...mapState('fraMonitoring', [
      'ftmFleetList'
    ]),
    ...mapGetters('fraMonitoringSetting', [
      'fleetMonitorDataF'
    ]),
    ...mapGetters('user', [
      'userInfo'
    ]),
    oooiStep() {
      let step = 1;
      let time = '';
      const { outTime, offTime, onTime, inTime, phase, latestAcarsTime } = this.fleetMonitorDataF;

      if (inTime) {
        step = 5;
        time = this.$moment.utc(inTime).format('HH:mm');
      } else if (onTime) {
        step = 4;
        time = this.$moment.utc(onTime).format('HH:mm');
      } else if (phase === 'ER') {
        step = 3;
        time = latestAcarsTime ? this.$moment.utc(latestAcarsTime).format('HH:mm') : this.$moment.utc(offTime).format('HH:mm');
      } else if (offTime) {
        step = 2;
        time = this.$moment.utc(offTime).format('HH:mm');
      } else if (outTime) {
        step = 1;
        time = this.$moment.utc(outTime).format('HH:mm');
      }
      return { step, time };
    },
    isEf: {
      get() {
        return Boolean(this.dataForm.isEf);
      },
      set(nv) {
        this.$set(this.dataForm, 'isEf', +nv);
      }
    },
    isNow: {
      get() {
        return Boolean(this.dataForm.isNow);
      },
      set(nv) {
        this.$set(this.dataForm, 'isNow', +nv);
      }
    },
    isMute: {
      get() {
        return Boolean(Math.abs(this.dataForm.isMute - 1));
      },
      set(nv) {
        this.$set(this.dataForm, 'isMute', +!nv);
      }
    },
    isActivity: {
      get() {
        return Boolean(this.dataForm.isActivity);
      },
      set(nv) {
        this.$set(this.dataForm, 'isActivity', +nv);
      }
    },
    otherItem: {
      get() {
        return Boolean(this.dataForm.otherItem);
      },
      set(nv) {
        this.$set(this.dataForm, 'otherItem', +nv);
      }
    },
    fmsBack() {
      return this.priorityHandler(this.fleetMonitorDataF?.priority ?? -1)?.color ?? 'transparent';
    }
    // deletedBy() {
    //   let rt = '--';
    //   if (typeof this.fleetMonitorDataF.specialFields === 'string') {
    //     try {
    //       rt = JSON.parse(this.fleetMonitorDataF.specialFields)['deleted_by'] || '--';
    //     } catch (error) {
    //       rt = '--';
    //     }
    //   } else if (typeof this.fleetMonitorDataF.specialFields === 'object') {
    //     rt = this.fleetMonitorDataF.specialFields?.deleted_by?.[0] ?? '--';
    //   }
    //   return rt;
    // }
  },
  watch: {
    'fleetMonitorDataF': {
      handler(v) {
        if (v.isMute && v.priority && v.priority > 0) {
          setTimeout(() => {
            this.$nextTick(() => {
              this.$store.dispatch('setting/messageAudioHandler',this.userInfo.userId);
            });
          }, 0);
        }
      },
      deep: true
    },
    configData: {
      handler(v) {
        if (v) {
          const { dep, arr, model, fleet, eventType, priority, isActivity, otherItem, isMute, isNow, isEf } = v;
          this.dataForm.isAndOr = dep && arr ? 0 : 1;
          this.dataForm.isActivity = isActivity ?? 1;
          this.dataForm.otherItem = otherItem ?? 0;
          this.dataForm.isMute = isMute ?? 1;
          this.dataForm.isNow = isNow ?? 1;
          this.dataForm.isEf = isEf ?? 1;
          dep ? this.dataForm.dep = dep : '';
          arr ? this.dataForm.arr = arr : '';
          Object.prototype.toString.call(model) !== '[object Null]' ? this.dataForm.model = model : '';
          Object.prototype.toString.call(fleet) !== '[object Null]' ? this.dataForm.fleet = fleet : '';
          Object.prototype.toString.call(eventType) !== '[object Null]' ? this.$set(this.dataForm, 'type', eventType) : '';
          Object.prototype.toString.call(priority) !== '[object Null]' ? this.dataForm.priority = priority : '';
        }
      },
      deep: true
    }

  },
  mounted() {
    document.onmousemove = (event) => {
      var posX = 0;
      var e = event || window.event; // 标准化事件对象
      if (e.pageX) { // 获取鼠标指针的当前坐标值
        posX = e.pageX;
      } else if (e.clientX) {
        posX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
      }
      if (posX < 200) {
        this.width = 0;
      } else {
        this.width = 200;
      }

      if (posX > document.body.clientWidth - 200) {
        this.rWidth = 0;
      } else {
        this.rWidth = 200;
      }
    };

    // this.fleetMonitorAll();
    this.fleetMonitorConfigByUser();
    // this.submitHandler();
    this.countdownHandler();

    // if (this.$route.params?.m) {
    //   this[this.$route.params?.m] = true;
    // }
  },
  beforeDestroy() {
    clearTimeout(this.setTime);
  },
  methods: {
    ...mapActions('fraMonitoringSetting', [
      'fleetMonitor',
      'fleetMonitorByStatus',
      'fleetMonitorAll',
      'saveFtmMonitor',
      'fleetMonitorConfigByUser'
    ]),
    ...mapMutations('fraMonitoringSetting', [
      'setState'
    ]),
    ...mapMutations('fraMonitoring', {
      'setFMState': 'setState'
    }),
    nexHandler() {
      this.setState({ key: 'allAcIndex', payload: this.allAcIndex + 1 });
    },

    // 关闭侧弹窗
    closeDrawerHandler(flag) {
      this.setFMState({ key: flag, payload: false });
    },
    countdownHandler() {
      if (this.now === 1) {
        this.now = 60;
        this.getData();
      } else {
        this.now -= 1;
      }
      this.setTime = setTimeout(() => {
        this.countdownHandler();
      }, 1000);
    },

    getData() {
      if (this.configId) {
        this.fleetMonitor();
      } else {
        this.fleetMonitorAll();
      }
    },
    reportHandlerFH(record, flag) {
      localStorage.setItem('scRow', JSON.stringify({ ...record }));
      this.setFMState({ key: flag, payload: true });
    },
    reportHandler(e, record, flag, index, select = false) {
      e.stopPropagation();
      this.currentRow = {
        ...record,
        id: record.legId,
        totalLeg: 0 - record.nowLeg
      };
      if (flag === 'eventDetailsVisible') {
        localStorage.setItem('eRow', JSON.stringify(this.currentRow));
      } else {
        localStorage.setItem('row', JSON.stringify(this.currentRow));
      }

      if (flag === 'taskResearchVisible') {
        localStorage.setItem('trRow', JSON.stringify({ ...record }));
        if (this.$store.state.setting.openType === '_self') {
          this.$router.push({ path: 'taskResearch', query: { m: '1' }});
        } else {
          const uuid = new Date().getTime();
          const routeData = this.$router.resolve({ path: 'taskResearch', query: { m: '1', uuid }});
          window.open(routeData.href, this.$store.state.setting.openType);
        }
      }
      this.setFMState({ key: flag, payload: true });
    },
    resetHandler() {
      this.fleetMonitorByStatus().then(res => {
        if (res) {
          this.setState({ key: 'allAcIndex', payload: 0 });
          // this.setState({ key: 'configId', payload: '' });
          this.setState({ key: 'fleetMonitorData', payload: [] });
          // this.submitHandler();
          this.dataForm = {
            isAndOr: 1,
            isEf: 1,
            isNow: 1,
            isMute: 1,
            isActivity: 1,
            otherItem: 0
          };
        }
      });
    },
    submitHandler() {
      // this.$refs.dataForm.validate(valid => {
      //   if (valid) {

      //   } else {
      //     console.log('error submit!!');
      //     return false;
      //   }
      // });
      const params = {
        ...this.dataForm,

        userId: this.userInfo.userId
      };
      for (const key in params) {
        if (Object.hasOwnProperty.call(params, key)) {
          const element = params[key];
          if (element === '' || element?.length === 0) {
            delete params[key];
          }
        }
      }
      this.setState({ key: 'allAcIndex', payload: 0 });
      this.saveFtmMonitor(params);
    }
  }
};
</script>

<style lang="less">
 @import 'index.less';
</style>
